<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/24 0024
 * Time: 下午 5:48
 */

namespace app\index\controller;

use app\admin\model\User;
use think\Request;
use think\Session;
use Wxpay\Wechat;

class WechatManage extends Common
{
    /**
     * @title   微信绑定操作
     * @return mixed
     */
    public function bindWechat()
    {
        if(Request::instance()->isAjax()){
            (new User())->save(['u_openid'=>'','u_head'=>''],['id'=>Session::get('userid')]);
            $this->success('已解除绑定');
        }
        $user = User::get(Session::get('userid'));
        $this->assign('user',$user);
        $this->assign('url',urlencode(url('WechatManage/bind@'.$_SERVER['HTTP_HOST'])));
        return $this->fetch('index/bind');
    }

    /**
     * @title   绑定微信
     */
    public function bind()
    {
        Wechat::setAppId(v('wechat.appid'));
        Wechat::setAppSecret(v('wechat.appsecret'));
        $oauth = Wechat::oauth(input('get.code'));
        $ret = Wechat::getUserInfo($oauth['access_token'],$oauth['openid']);
        (new User())->save(['u_openid'=>$ret['openid'],'u_head'=>$ret['headimgurl']],['id'=>Session::get('userid')]);
        $this->redirect('WechatManage/bindWechat');
    }
}